package thoven.achievement.net.jsonutil.intention

import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import thoven.achievement.net.jsonutil.service.JsonCleaner
import thoven.achievement.net.jsonutil.service.JsonFormatter

/**
 * 格式化 JSON 的意图操作
 */
class FormatJsonIntention : PsiElementBaseIntentionAction(), IntentionAction {
    
    override fun getText(): String = "格式化 JSON"
    
    override fun getFamilyName(): String = "JSON Utilities"
    
    override fun isAvailable(project: Project, editor: Editor?, element: PsiElement): Boolean {
        if (editor == null) return false
        
        val selectionModel = editor.selectionModel
        if (!selectionModel.hasSelection()) return false
        
        val selectedText = selectionModel.selectedText ?: return false
        
        // 简单检测是否可能是 JSON
        val trimmed = selectedText.trim()
        return trimmed.startsWith("{") || trimmed.startsWith("[") ||
                trimmed.contains("\"") || trimmed.contains(":")
    }
    
    override fun invoke(project: Project, editor: Editor?, element: PsiElement) {
        if (editor == null) return
        
        val selectionModel = editor.selectionModel
        val selectedText = selectionModel.selectedText ?: return
        
        val cleanResult = JsonCleaner.clean(selectedText)
        val cleanedJson = cleanResult.getOrNull() ?: return
        
        val formatResult = JsonFormatter.format(cleanedJson)
        val formattedJson = formatResult.getOrNull() ?: return
        
        WriteCommandAction.runWriteCommandAction(project) {
            editor.document.replaceString(
                selectionModel.selectionStart,
                selectionModel.selectionEnd,
                formattedJson
            )
        }
    }
}

